package org.praktika.api.service;

import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.praktika.api.dto.ClientDto;
import org.praktika.api.entity.Client;
import org.praktika.api.repository.ClientRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class ClientService {
    private final ClientRepository clientRepository;
    private final ModelMapper modelMapper = new ModelMapper();

    @Transactional
    public ClientDto saveClient  (ClientDto clientDto) {
        Client client = modelMapper.map(clientDto, Client.class);
        clientRepository.save(client);
        return modelMapper.map(client, ClientDto.class);
    }
    public ClientDto getClientDtoById(Long id) {
        return modelMapper.map(getClientById(id), ClientDto.class);
    }

    public Client getClientById(Long id) {
        Optional<Client> client = clientRepository.findById(id);
        return client.orElseThrow(() -> new RuntimeException("No client found"));
    }

    @Transactional
    public ClientDto updateClient(ClientDto clientDto) {
        Client client = getClientById(clientDto.getId());
        client.setFullName(clientDto.getFullName());
        client.setDob(clientDto.getDob());
        client.setPhone(clientDto.getPhone());
        clientRepository.save(client);
        return modelMapper.map(client, ClientDto.class);
    }

    @Transactional
    public void deleteClient(Long id) {
        clientRepository.deleteById(id);
    }

    public List<ClientDto> findAllClients() {
        List<Client> clients = clientRepository.findAll();
        List<ClientDto> clientDtos = new ArrayList<>();
        clients.forEach(client -> clientDtos.add(modelMapper.map(client, ClientDto.class)));
        return clientDtos;
    }
}
